from django.shortcuts import render
from django.views.generic.base import View
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.urls import reverse
from apps.users.form import LoginForm, CapchaLoginForm


# Create your views here.
# 退出登录
class LogoutView(View):
    def get(self, request, *args, **kwargs):
        logout(request)
        return HttpResponseRedirect(reverse("index"))


# 登录
class LoginView(View):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return render(request, "index.html")
        else:
            login_form = CapchaLoginForm
            return render(request, "login.html", {
                "login_form": login_form
            })
    def post(self, request, *args, **kwargs):
        form = LoginForm(request.POST)
        if form.is_valid():
            # 检测账号密码是否匹配
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                # 会重定向 url
                return HttpResponseRedirect(reverse("index"))
            else:
                return render(request, "login.html", {'msg': "账号或密码错误"})
        else:
            return render(request, "login.html", {'msg': "账号或密码错误"})
